﻿$(function () {
    var cardViewThreshold = 580;
    /* Set a locale manually */
    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US']);
    loaddata();
    
    /* Auto adjust the table's view type (table/card) when screen size changes */
    //window.onresize = function () {
    //    $('#table').bootstrapTable('refreshOptions', {
    //        cardView: document.body.clientWidth < cardViewThreshold
    //    });
    //};
});
function reloaddata() {
    //var opt = {
    //    url: "/lxoa/listvacation/"
    //};
    //$('#table').bootstrapTable('refresh', opt);

    $.ajax({
        url: '/lxoa/listuser/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.total > 0) {
                $("#table").bootstrapTable('load', data.rows);
            } else {
                //alert('error');
            }
        }
    })  
}

var gid = 0;
function opendelconfirm() {
    if (selectrow != null && selectrow.id != null && selectrow.id > 0) {
        gid = selectrow.id;
        $("#myModaldel").modal("show");
    }
}

function loaddata() {
    $.ajax({
        url: '/lxoa/listuser/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },  
        success: function (data) {
            if (data && data.total>0) {
                binddata(data.rows);
                $('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title="添加"> 添加 </button>&nbsp;&nbsp;<button class="btn btn-primary" type="button" onclick="opendelconfirm()" style="margin-left:4px;" title="删除"> 删除 </button>&nbsp;&nbsp;<button class="btn btn-primary" type="button" onclick="openeditconfirm()" style="margin-left:4px;" title="编辑"> 编辑 </button>');
                $('.keep-open').hide();
                //getuserlist();//order last one load it.
                //alert('success');
            } else {
                if (data && data.total == -1) {
                    $('#divrole').show().html("<h4> 无权访问，请联系管理员！</h4>");
                }
                //alert('error');
            }
        }
    })
}
var selectrow;
function binddata(datas) {
    var cardViewThreshold = 580;
    $('#table').bootstrapTable({
        cardView: document.body.clientWidth < cardViewThreshold,
        //striped: true,
        search: true,
        pagination: true,
        ageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 50],
        showColumns: true,
        showToggle: false,
        //showExport: true,
        columns: [
            {
                title: '序号',
                field: '',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },{
            field: 'username',
            title: '姓名',
            sortable: true
        }, 
        {
            field: 'useremail',
            title: '邮箱',
            sortable: true
            },
        {
            field: 'temp',
            title: '所属部门',
            sortable: true
        },
        {
            field: 'entrydate',
            title: '入职时间',
            sortable: true
        },
        {
            field: 'userresume',
            title: '简历',
            //sortable: true,
            formatter: aFormatter
        }],
        data: datas
    });

    $('#table').on('click-row.bs.table', function (e, row, element) {
        $('.success').removeClass('success');
        $(element).parent().find('tr').css('background', 'none')
        //$(element).css('background', 'none');
        $(element).css('background', 'lightgrey');
        $(element).addClass('success');
        //$(element).css('background-color', '#fff');
        selectrow = row;
        //var index = $('#table').find('tr.success').data('index');
    });
}

function aFormatter(value, row, index) {
    if (value && value.length>0) {
        return ['<a href="/lxoa/file_down?filename=' + value + '">下载</a>'].join("");
    } else {
        return ['<a href="#">暂无</a>'].join("");
    }   
}

function getuserlist() {
    $.ajax({
        url: '/lxoa/getuserlist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.length > 0) {
                $("#vac_person").empty();
                $("#vac_person2").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#vac_person").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                    $("#vac_person2").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                }
                //alert('success');
            } else {
                //alert('error');
            }
        }
    })
}

$(document).ready(function () {
    setTimeout(function () { $('.webuploader-pick').next().attr('style', 'width:86px;height:40px;position: absolute;top: 0px;left: 0px;'); $($('.webuploader-pick')[1]).next().attr('style', 'width:86px;height:40px;position: absolute;top: 0px;left: 0px;'); }, 2000);
});
Date.prototype.addDays = function (day, number) {
    var adjustDate = new Date(day + 24 * 60 * 60 * 1000 * 30 * number)
    //alert("Date" + adjustDate.getFullYear() + "-" + adjustDate.getMonth() + "-" + adjustDate.getDate());
    return adjustDate;
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds() //??
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addDays2 = function (d) {
    this.setDate(this.getDate() + d);
    return this.Format('yyyy-MM-dd');
};
laydate.render({
    elem: '#entrydate',
    lang: 'zh',
    done: function (value, date, endDate) {
        if (value && value.length > 0) {
            $('#vac_date').attr('style', 'border:1px solid #ccc;');
            var curDate = new Date(value);
            $('#vac_enddate').val(curDate.addDays2(parseFloat($('#vac_interval').val())));
        } else {
            $('#vac_enddate').val('');
        }
    }
});

$("#submitbtn").click(function () {
    var uname = $('#username');
    var upwd = $('#userpwd');
    var umail = $('#usermail');
    //var files = $('#files');
    var entdate = $('#entrydate');
    var utype = $('#selectdep');
    if (uname.val().length < 1) {
        uname.attr('style', 'border:1px solid red;');
        uname.focus();
        return;
    }
    if (upwd.val().length < 5) {
        upwd.attr('style', 'border:1px solid red;');
        upwd.focus();
        return;
    }
    if (umail.val().length < 1) {
        umail.attr('style', 'border:1px solid red;');
        umail.focus();
        return;
    } else {
        var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (!myreg.test(umail.val())) {
            umail.attr('style', 'border:1px solid red;');
            umail.focus();
            return;
        }
    }
    if (entdate.val().length < 1) {
        entdate.attr('style', 'border:1px solid red;');
        return;
    }

    $.ajax({
        url: '/lxoa/saveuser/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: {
            username: uname.val(),
            userpwd: upwd.val(),
            usermail: umail.val(),
            userresume: $('#resumefiles').val(),
            entrydate: entdate.val(),
            udept: utype.val(),
            temp: utype.find("option:selected").text()
        },
        success: function (data) {
            if (data && data.success == '1') {
                $('#myAlert').removeClass('hidden');
                cleartxt();
                setTimeout(function () {
                    $('#myModal').modal('hide');
                    $('#myAlert').addClass('hidden');
                    reloaddata();
                }, 1000);

            } else {
                $('#myAlerterror').removeClass('hidden');
                setTimeout(function () {
                    $('#myAlerterror').addClass('hidden');
                }, 1500);
            }
        }
    })

})

function cleartxt() {
    $('#username').val('').attr('style', 'border:1px solid #ccc;');
    $('#userpwd').val('').attr('style', 'border:1px solid #ccc;');
    $('#usermail').val('').attr('style', 'border:1px solid #ccc;');
    $('#entrydate').val('').attr('style', 'border:1px solid #ccc;');
    $('#thelist').html('');//clear upload hoistory
}
function cleartxtedit() {
    $('#username2').val('').attr('style', 'border:1px solid #ccc;');
    $('#userpwd2').val('').attr('style', 'border:1px solid #ccc;');
    $('#usermail2').val('').attr('style', 'border:1px solid #ccc;');
    $('#entrydate2').val('').attr('style', 'border:1px solid #ccc;');
    $('#thelist2').html('');//clear upload hoistory
}

function deluser() {
    if (gid == 0) {
        alert("请选择要删除的项！");
        return;
    }
    $.ajax({
        url: '/lxoa/deluser/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: {
            id: gid
        },
        success: function (data) {
            if (data && data.success == '1') {
                $('#myModaldel').modal('hide');
                reloaddata();
            } else {
                $('#myModaldel').modal('hide');
                alert('删除失败，请稍后重试！');
            }
        }
    })
}

function openeditconfirm() {
    if (selectrow != null && selectrow.id != null && selectrow.id > 0) {
        gid = selectrow.id;
        $("#myModaledit").modal("show");

        $('#username2').val(selectrow.username);
        //$('#userpwd2').val('');
        $('#usermail2').val(selectrow.useremail);
        $('#entrydate2').val(selectrow.entrydate);
        $('#selectdep2').val(selectrow.userdepartment);
        $('#thelist2').html('');//clear upload hoistory

    }
}

function editsubmit() {
    if (selectrow == null || selectrow.id == null || selectrow.id < 1) {
        return;
    }
    var uname = $('#username2');
    var upwd = $('#userpwd2');
    var umail = $('#usermail2');
    //var files = $('#files');
    var entdate = $('#entrydate2');
    var utype = $('#selectdep2');
    if (uname.val().length < 1) {
        uname.attr('style', 'border:1px solid red;');
        return;
    }
    if (upwd.val().length < 5) {
        upwd.attr('style', 'border:1px solid red;');
        return;
    }
    if (umail.val().length < 1) {
        umail.attr('style', 'border:1px solid red;');
        return;
    } else {
        var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (!myreg.test(umail.val())) {
            umail.attr('style', 'border:1px solid red;');
            umail.focus();
            return;
        }
    }
    if (entdate.val().length < 1) {
        entdate.attr('style', 'border:1px solid red;');
        return;
    }

    $.ajax({
        url: '/lxoa/edituser/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: {
            username: uname.val(),
            userpwd: upwd.val(),
            usermail: umail.val(),
            userresume: $('#resumefiles2').val(),
            entrydate: entdate.val(),
            udept: utype.val(),
            temp: utype.find("option:selected").text(),
            id: gid
        },
        success: function (data) {
            if (data && data.success == '1') {
                $('#myAlert2').removeClass('hidden');
                cleartxtedit();
                setTimeout(function () {
                    $('#myModaledit').modal('hide');
                    $('#myAlert2').addClass('hidden');
                    reloaddata();
                }, 1000);

            } else {
                $('#myAlerterror2').removeClass('hidden');
                setTimeout(function () {
                    $('#myAlerterror2').addClass('hidden');
                }, 1500);
            }
        }
    })
}